import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_category.dart';
import 'package:flutter_learn_vi/src/bean/bean_mine.dart';
import 'package:flutter_learn_vi/src/bean/bean_video.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/news/news_request_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/7/23.
///
/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/9/25.
///
/// gongzhonghao biglead
/// https://study.163.com/instructor/1021406098.htm
/// https://blog.csdn.net/zl18603543572
/// https://www.toutiao.com/c/user/token/MS4wLjABAAAAYMrKikomuQJ4d-cPaeBqtAK2cQY697Pv9xIyyDhtwIM/

///lib/page/catalogue/catalogue_main_page.dart
///目录主页面
class CatalogueMainPage extends StatefulWidget {
  final int pageIndex;
  final MineBean mineBean;
  final bool showAppBar;

  CatalogueMainPage(this.pageIndex, {this.mineBean, this.showAppBar = true});

  @override
  State<StatefulWidget> createState() {
    return _CatalogueMainPageState();
  }
}

class _CatalogueMainPageState extends State<CatalogueMainPage>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  ///页面保持状态
  @override
  bool get wantKeepAlive => true;

  //推荐模拟数据
  List<VideoModel> videoList = [];

  //控制器
  TabController _tabController;

  //Tab集合
  List<Tab> tabs = <Tab>[];

  //主体页面的集合
  List<Widget> bodyList = [];

  String title;

  @override
  void initState() {
    super.initState();

    if (widget.pageIndex == 1) {
      title = "矿内党建";
    } else {
      title = "矿内新闻";
    }

    getCategorys();
  }

  List<CategoryBean> _categoryList = [];

  Future<bool> getCategorys() async {
    Map<String, dynamic> map = Map();
    if (widget.mineBean != null) {
      map["selectMineId"] = widget.mineBean.id;
    }

    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.newstype,
      queryParameters: map,
    );
    if (responseInfo.success) {
      List list = responseInfo.data;
      _categoryList = [];
      list.forEach((element) {
        CategoryBean newsBean = CategoryBean.fromJson(element);
        _categoryList.add(newsBean);
      });
    }

    initView();

    return Future.value(true);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (_tabController == null) {
      return Scaffold(
        appBar: buildAppBar(),
        body: Center(
          child: LoadingWidget(),
        ),
      );
    }
    if (widget.mineBean != null) {
      return Column(
        children: [
          Container(
            color: Colors.white,
            width: double.infinity,
            child: Material(
                color: Colors.white,
                child: Container(width: double.infinity, child: buildTabBar())),
          ),
          Expanded(
            child: buildTabBarView(context),
          ),
        ],
      );
    }
    return Scaffold(
      appBar: buildAppBar(),
      body: RefreshIndicator(
        onRefresh: () {
          return Future.value(true);
        },
        child: buildTabBarView(context),
        // child: Column(
        //   children: [
        //     Material(
        //         color: Colors.white,
        //         child: Container(width: double.infinity, child: buildTabBar())),
        //     Expanded(child: buildTabBarView(context)),
        //   ],
        // ),
      ),
    );
  }

  AppBar buildAppBar() {
    if (!widget.showAppBar) {
      return null;
    }
    return widget.mineBean == null
        ? AppBar(
            centerTitle: true,
            title: Text("$title"),
          )
        : null;
  }

  TabBar buildTabBar() {
    return TabBar(
      //可以和TabBarView关联使用同一个TabController
      controller: _tabController,
      //子Tab
      tabs: tabs,
      isScrollable: true,
    );
  }

  Widget buildTabBarView(BuildContext context) {
    return TabBarView(
      physics: NeverScrollableScrollPhysics(),
      //联动控制器
      controller: _tabController,
      //所有的子页面
      children: bodyList,
    );
  }

  int pageIndex = 1;

  void initView() {
    List<CategoryItemBean> itemList = [];

    if (widget.pageIndex == 1) {
      itemList = _categoryList[1].children;
    } else {
      itemList = _categoryList[0].children;
    }

    //初始化Tab 如新闻资讯类型的APP的分类
    tabs = <Tab>[];

    // itemList.forEach((element) {
    //   tabs.add(Tab(
    //     text: element.categoryName,
    //   ));
    // });
    if (itemList.isNotEmpty) {
      tabs.add(Tab(
        text: itemList[0].categoryName,
      ));
      //创建模拟页面 如新闻资讯类型的APP的分类列表
      for (int i = 0; i < tabs.length; i++) {
        bodyList.add(
          NewsItemRequestPage(
            mineBean: widget.mineBean,
            itemBean: itemList[i],
            pageIndex: widget.pageIndex,
            key: ValueKey(""
                "$i"),
          ),
        );
      }
      //initialIndex初始选中第几个
      //[length] 标签的个数
      //[vsync]动画同步依赖
      _tabController = TabController(initialIndex: 0, length: 1, vsync: this);
    }

    setState(() {});
  }
}
